package com.zhicheng.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhicheng.exception.BaseException;
import com.zhicheng.mapper.*;
import com.zhicheng.pojo.*;
import com.zhicheng.pojo.dto.CreOrderDTO;
import com.zhicheng.pojo.result.PageResult;
import com.zhicheng.pojo.vo.GoodVO;
import com.zhicheng.pojo.vo.OrderSummaryVO;
import com.zhicheng.pojo.vo.OrderVO;
import com.zhicheng.pojo.vo.PreOrderVO;
import com.zhicheng.service.OrderService;
import com.zhicheng.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GoodMapper goodMapper;

    @Override
    public PreOrderVO preOrder() {
        Long userId = ThreadLocalUtil.getCurrentId();
        //查询地址簿
        List<AddressBook> addressBook = addressBookMapper.getByUserId(userId);
        if (addressBook == null) {
            throw new BaseException("用户地址为空，不能下单");
        }
        //查询购物车商品
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.orderList(shoppingCart);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new BaseException("购物车数据为空，不能下单");
        }
        //统计商品价格
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (ShoppingCart cart : shoppingCarts) {
            totalPrice = totalPrice.add(cart.getPrice());
        }
        OrderSummaryVO orderSummaryVO = new OrderSummaryVO();
        orderSummaryVO.setTotalNum(shoppingCarts.size());
        orderSummaryVO.setTotalPrice(totalPrice);
        orderSummaryVO.setPostFee(new BigDecimal(10));
        orderSummaryVO.setPayAmount(orderSummaryVO.getTotalPrice().add(orderSummaryVO.getPostFee()));

        //封装VO返回结果
        PreOrderVO preOrderVO = PreOrderVO.builder()
                .userAddresses(addressBook)
                .goods(shoppingCarts)
                .summary(orderSummaryVO)
                .build();

        return preOrderVO;
    }

    @Override
    public Order creOrder(CreOrderDTO creOrderDTO) {
        Long userId = ThreadLocalUtil.getCurrentId();
        User user = userMapper.getUserById(userId);

        AddressBook address = addressBookMapper.getByAddressId(creOrderDTO.getAddressId());
        if (address == null) {
            throw new BaseException("收货地址为空，不能下单");
        }
        String detail = address.getProvinceName() + " " + address.getCityName() + " " + address.getDistrictName() + " " + address.getDetail();

        // 向订单表插入一条数据
        Order order = new Order();
        BeanUtils.copyProperties(creOrderDTO.getSummary(),order);
        order.setId(String.valueOf(System.currentTimeMillis()));
        order.setOrderStatus(Order.PENDING_PAYMENT);
        order.setGoodsId(creOrderDTO.getGoods());
        order.setUserId(userId);
        order.setUserName(user.getNickname());
        order.setAddressBookId(address.getId());
        order.setConsignee(address.getConsignee());
        order.setPhone(address.getPhone());
        order.setAddress(detail);
        order.setOrderTime(LocalDateTime.now());
        order.setPayChannel(creOrderDTO.getPayChannel());
        order.setPayType(creOrderDTO.getPayType());
        order.setPayStatus(Order.UN_PAID);
        order.setDeliveryTimeType(creOrderDTO.getDeliveryTimeType());
        order.setCreateTime(LocalDateTime.now());
        order.setPayLatestTime(LocalDateTime.now().plusMinutes(30));
        orderMapper.creOrder(order);

        // 下单成功后，清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        return order;
    }

    @Override
    public Order getByOrderId(String id) {
        return orderMapper.getByOrderId(id);
    }

    @Override
    public PageResult<OrderVO> getByUserId(Integer orderStatus, int page, int pageSize) {
        //1.创建PageResult对象
        PageResult<OrderVO> pageResult =new PageResult<>();
        //2.开启分页查询PageHelper
        PageHelper.startPage(page, pageSize);
        Long userId = ThreadLocalUtil.getCurrentId();
        List<OrderVO> orderList = orderMapper.getByUserId(userId,orderStatus);
        //查询订单中的商品信息
        for (OrderVO order:orderList) {
            if (order.getPayLatestTime().isBefore(LocalDateTime.now())  && order.getOrderStatus() == 1){
                order.setOrderStatus(6);
                orderMapper.updateOrderStatus(order);
            }
            OrderVO o = new OrderVO();
            o.setId(order.getId());
            //将goodIds以逗号分隔成一个数组goodIds
            String[] goodIds = order.getGoodsId().split(",");
            // 移除id两端的空白，并将id解析为一个Long基本类型
            List<Long> ids = Arrays.stream(goodIds)
                    .map(String::trim)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            // 使用for循环遍历ID列表
            List<GoodVO> goods = new ArrayList<>();
            for (Long id : ids) {
                // 使用ID查询数据
                GoodVO goodVO = goodMapper.getGoodsById(id);
                // 将查询到的数据添加到新列表中
                goods.add(goodVO);
            }
            // 把数据填充到当前的order对象
            order.setGoods(goods);
        }
        //Page中提供了方法，可以获取PageHelper分页查询后得到的总记录数和当前页数据
        Page<OrderVO> p = (Page<OrderVO>) orderList;
        //把数据填充到PageResult对象中
        pageResult.setTotal(p.getTotal());
        pageResult.setItems(p.getResult());
        pageResult.setPages(p.getPages());
        pageResult.setPage(p.getPageNum());
        pageResult.setPageSize(p.getPageSize());
        return pageResult;

    }
}
